package com.ifar.audiosdk.activity

import android.media.AudioManager
import android.view.SurfaceView
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.BarUtils
import com.ifar.audiosdk.R
import com.ifar.audiosdk.base.EngineBaseActivity
import com.ifar.audiosdk.common.IfarConfig
import com.ifar.audiosdk.common.IfarEventBusTag
import com.ifar.audiosdk.model.main.viewmodel.MainViewModel
import com.ifar.audiosdk.utils.GlassHandle
import com.ifar.audiosdk.utils.IfarVideoSource
import io.agora.rtc.mediaio.AgoraDefaultRender
import io.agora.rtc.mediaio.AgoraDefaultSource
import io.agora.rtc.mediaio.AgoraSurfaceView
import io.agora.rtc.mediaio.MediaIO
import kotlinx.android.synthetic.main.activity_chat.*
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import org.simple.eventbus.ThreadMode

@Route(path = "/app/CallActivity")
class CallActivity : EngineBaseActivity<MainViewModel>() {
    override fun getLayoutResId() = R.layout.activity_chat

    @Autowired
    lateinit var channelId: String

    @Autowired
    lateinit var token: String

    private val localUid = IfarConfig.peer_id.toInt()

    override fun initView() {
        BarUtils.setStatusBarVisibility(this, false)
    }

    override fun initData() {
        doConfigEngine()
        //本地预览画面
        if (GlassHandle.isGlassConnect) {
            GlassHandle.openCamera()
            initSurface()
            ctvGlassSurface.visibility = View.VISIBLE
            GlassHandle.actionSurfaceView(ctvGlassSurface)
        } else {
            rtcEngine().setLocalVideoRenderer(AgoraDefaultRender())
            rtcEngine().setVideoSource(AgoraDefaultSource())
            ctvGlassSurface.visibility = View.GONE
            saveLocalVideo(localUid, fl_local1)
            loadVideo(localUid, fl_local1)
        }

        joinChannel(channelId, localUid, token)
        volumeControlStream = AudioManager.STREAM_VOICE_CALL
    }

    /**眼镜视频自采集*/
    private fun initSurface() {
        val agoraSurfaceView = AgoraSurfaceView(this)
        agoraSurfaceView.setZOrderOnTop(true)
        agoraSurfaceView.setZOrderMediaOverlay(true)
        agoraSurfaceView.setBufferType(MediaIO.BufferType.BYTE_ARRAY)
        agoraSurfaceView.setPixelFormat(MediaIO.PixelFormat.NV21)
        rtcEngine().setLocalVideoRenderer(agoraSurfaceView)
        rtcEngine().setVideoSource(IfarVideoSource())
    }

    /**初始化声网参数*/
    private fun doConfigEngine() {
        rtcEngine().setClientRole(1)
        configEngine()
    }

    /**释放资源*/
    override fun deInitUIandEvent() {
        doLeaveChannel()
        mVideos.clear()
        if (GlassHandle.isGlassConnect) {
            GlassHandle.closeCamera()
        }
    }

    /**离开频道*/
    private fun doLeaveChannel() {
        leaveChannel()
        preview(false, SurfaceView(mContext), localUid)
    }

    /**有用户进入频道*/
    private fun doRenderRemoteUi(uid: Int) {
        saveRemoteVideo(uid)
        loadVideo(uid, fl_remote)
    }

    @Subscriber(tag = IfarEventBusTag.ON_FIRST_REMOTE_VIDEO_DECODED, mode = ThreadMode.MAIN)
    fun onFirstRemoteVideoDecoded(uid: Int) {
        doRenderRemoteUi(uid)
    }

    @Subscriber(tag = IfarEventBusTag.ON_USER_OFFLINE, mode = ThreadMode.MAIN)
    fun onUserOffline(uid: Int) {
        mVideos.remove(uid)
        val bool = if (GlassHandle.isGlassConnect && mVideos.isEmpty()) true
        else !GlassHandle.isGlassConnect && mVideos.size == 1

        if (bool) {    //判断房间只剩下自己的时候退出频道
            finish()
            EventBus.getDefault().post("", IfarEventBusTag.CALLING_HANGUP)
        }

    }

    override fun onBackPressed() {
        EventBus.getDefault().post("", IfarEventBusTag.CALLING_HANGUP)
        super.onBackPressed()
    }
}